import { CSSProperties, Children, cloneElement, isValidElement, useMemo } from 'react';
import classNames from 'classnames';
import theme from '@/theme';
import Row from '../Row';
import Text from '../Text';

import './index.scss';
import { StandardProps } from '@tarojs/components';
import Icon from '../Icon';
import { pxTransform } from '@tarojs/taro';

const sizes = {
  s: 18,
  m: 1,
  l: 4,
};

const iconSizes = {
  s: 18,
  m: 22,
  l: 26,
};
const stringTypes = ['string', 'number', 'boolean'];

interface TagProps extends StandardProps {
  /** 标签类型 */
  type?: 'default' | 'primary' | 'secondary' | 'success' | 'warning' | 'danger' | 'custom1' | 'custom2' | 'custom3';
  /** 标签大小 */
  size?: 's' | 'm' | 'l';
  /** 标签颜色 */
  color?: string;
  /** 文字颜色 */
  texColor?: string;
  /** 是否是空心标签 */
  plain?: boolean;
  /** 圆角类型 */
  radiusType?: 'square' | 'round' | 'round-min';
  /** 子元素 */
  children?: any;
  /** 是否可关闭 */
  closable?: boolean;
  onClose?: (e) => any;
  style?: CSSProperties;
}

const Tag = ({
  type = 'primary',
  size = 'm',
  color,
  texColor,
  plain,
  radiusType = theme.tag.radiusType as any,
  className,
  style,
  children,
  onClose,
  closable = false,
  ...props
}: TagProps) => {
  const _style = useMemo(() => {
    const _sty: CSSProperties = {};
    if (color) {
      if (plain) {
        _sty.borderColor = color;
        _sty.color = color;
      } else {
        _sty.backgroundColor = color;
      }
    }
    if (texColor) {
      _sty.color = texColor;
    }
    return _sty;
  }, [color, plain, texColor]);

  return (
    <Row
      className={classNames(
        'pd-tag',
        'pd-tag--' + radiusType,
        !plain && 'pd-tag--' + type,
        plain && 'pd-tag--plain pd-tag--plain--' + type,
        size && 'pd-tag--' + size,
        className,
      )}
      style={{ ...style, ..._style }}
      justify='center'
      items='center'
      {...props}>
      {Children.map(children, child => {
        if (stringTypes.includes(typeof child)) {
          return (
            <Text break {...(plain ? { type: type as any } : { color: texColor || 4 })} size={sizes[size]}>
              {child}
            </Text>
          );
        }
        // if (isValidElement(child)) {
        //   return cloneElement(child, {
        //     style: {
        //       ...child.props.style,
        //       color: '#fff'
        //     }
        //   })
        // }
        return child;
      })}
      {closable && (
        <Icon style={{ marginLeft: pxTransform(10) }} name='close' color={texColor || '#fff'} size={iconSizes[size]} onClick={onClose} />
      )}
    </Row>
  );
};
export default Tag;
